<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 

class Login extends MY_Controller {
	
	protected $restricted = false;
	private $salt;
	private $default_redirect;
	
	function Login() {
        parent::MY_Controller();
        
		$this->ci =& get_instance();
		$this->salt = $this->ci->config->item('encryption_key');
		
		$navigation = $this->ci->config->item('nav');
		$this->default_redirect = $navigation[0];
		
	}

	function index() {
		$this->load->helper('array');

		// Is SessionData available
		if($this->session->userdata('userdata') !== false)
			redirect($this->default_redirect);
	
		$l['redirect'] = $this->session->flashdata("redirect");
		
		if (strlen($this->session->flashdata("status")) > 0) {
			$l['status']  = $this->session->flashdata("status");
		}
		
		$data = $this->getData('login');

		// getQoutes
		$sql = "SELECT val FROM ".$this->tblc." WHERE name LIKE ?";
		$query = $this->db->query($sql, array("quotes"));
		$res = $query->result();
		if (count($res) > 0) {
			$quotes = json_decode($res[0]->val);
			$data['quotes'] = $quotes;		
		}

		$data["content"] = $this->load->view('login', $l, true);
		$this->load->view('layout', $data);
		
	}
	
	function forgotten() {
		$this->load->helper('array');

		$data = $this->getData('login');
		
		// getQoutes
		$sql = "SELECT val FROM ".$this->tblc." WHERE name LIKE ?";
		$query = $this->db->query($sql, array("quotes"));
		$res = $query->result();
		$quotes = json_decode($res[0]->val);
		$data['quotes'] = $quotes;		
		
				
		$data["content"] = $this->load->view('login-forgotten', '', true);
		
		$this->load->view('layout', $data);
	}

	
	function sendnewpw() {
		$login = $this->input->post('login');
		if (strlen($login) > 0) {
			redirect("login");
		}
		
		$username = $this->input->post('username');
		
		if (strlen($username) > 0) {
			
			$sql = "SELECT * FROM ".$this->tblu
				." WHERE username LIKE ?"
				." OR email LIKE ?";
			$query = $this->db->query($sql, array($username, $username));
			
			$res = $query->result();
			
			// Does username exist?
			if (sizeof($res) === 1) {
				$u = $res[0];

				// URL erzeugen!
				$url_username = str_replace("%", "-", urlencode(base64_encode($u->username)));
				$url_hash	  = str_replace("%", "-", urlencode(base64_encode($u->hash)));
				
				$url =  site_url("login/pw")."/".$url_username."/".$url_hash;

				
				// Email mit Link für die Generierung eines neuen Passwortes verschicken!
 				$subject = $this->ci->config->item('main_title')." - Passwort vergessen";
				$message =  "Hallo %s,\n\n" 
						."Mit einem Klick auf den unten stehenden Link wird ein neues Passwort generiert,"
						." dass dann per Email an %s geschickt wird.\n\n"
						."%s\n\n"
						."Gruß\n\n"
						."Tippmaster\n"
						."tippspiel@kozianka-online.de\n"
						."http://tipp.kozianka-online.de/\n";

				$message =  sprintf($message, $u->name, $u->email, $url);
				$this->email->from($this->ci->config->item('admin_email'), $this->ci->config->item('admin_name'));
				$this->email->to($u->email);

				$this->email->subject($subject);
				$this->email->message($message);	
				$this->email->send();				

				$this->session->set_flashdata("status_type", "info");
				$this->session->set_flashdata("status", sprintf(lang("login_username_email_email_sent"), $u->email));
				redirect("login/forgotten");
			}
			else {
				// Benutzer bzw. Emailadresse gibt es nicht
				$this->session->set_flashdata("status_type", "error");
				$this->session->set_flashdata("status", lang("login_username_email_does_not_exist"));
				redirect("login/forgotten");
			}
		}
		else {
			// Benutzer bzw. Emailadresse nicht angegeben
			$this->session->set_flashdata("status_type", "error");
			$this->session->set_flashdata("status", lang("login_username_email_required"));
			redirect("login/forgotten");
		}

	
	
	}
	
	function pw($url_username, $url_hash) {
		$username = base64_decode(urldecode(str_replace("-", "%", $url_username)));
		$hash	  = base64_decode(urldecode(str_replace("-", "%", $url_hash)));

		
		$sql = "SELECT * FROM ".$this->tblu
			." WHERE username LIKE ?"
			." AND hash LIKE ?";
		$query = $this->db->query($sql, array($username, $hash));

		$res = $query->result();
		
		// Does username exist?
		if (sizeof($res) === 1) {
			$u = $res[0];

			$new_password = $this->generatePW();
			$new_hash = sha1(microtime());
			$password_enc = sha1($this->salt.$new_hash.$new_password);

			$sql = "UPDATE ".$this->tblu." SET"
				." `hash` = ?,"
				." `password` = ?"
				." WHERE `id` = ? LIMIT 1";

			$query = $this->db->query($sql, array($new_hash, $password_enc, $u->id));
				
			if($this->db->affected_rows() > 0) {

				// Email mit Link für die Generierung eines neuen Passwortes verschicken!
	 			$subject = $this->ci->config->item('main_title')." - Neue Zugangsdaten";
				$message =  "Hallo %s!\n\n" 
						."Neue Zugangsdaten:\n\n"
						."Benutzer: %s\n"
						."Passwort: %s\n\n"
						."Gruß\n\n"
						."Tippmaster\n"
						."tippspiel@kozianka-online.de\n"
						."http://tipp.kozianka-online.de/\n";
	
				$message =  sprintf($message, $u->name, $u->username, $new_password);
				$this->email->from($this->ci->config->item('admin_email'), $this->ci->config->item('admin_name'));
				$this->email->to($u->email);
	
				$this->email->subject($subject);
				$this->email->message($message);	
				$this->email->send();
								
				redirect("");
				
			} // Query successfull		
			
			
		}

	}

	function process() {
		$forgotten = $this->input->post('forgotten');
		if (strlen($forgotten) > 0) {
			redirect("login/forgotten");
		}
		
		$this->load->library('form_validation');
		
		$data = $this->getData("login");

        $this->form_validation->set_rules('username', 'Username', 'trim|required');
        $this->form_validation->set_rules('password', 'Password', 'trim|required');

		$this->form_validation->set_error_delimiters('','<br/>'); // Set the the error tags.

		$flashdata = null;
		$redirect = $this->input->post('redirect');
		$flashdata->redirect = $redirect;

		if($this->form_validation->run()) {
			
			$username = $this->input->post('username');
			$passwd = $this->input->post('password'); 
			$login = $this->internalLogin($username, $passwd);
			
			if ($login === false) {
				// Login failed
				$flashdata->status_type = "error";
				$flashdata->status = $this->lang->line('login_failed');
				$this->session->set_flashdata($flashdata);
				redirect($this->loginPage);
			} else {
				// Login succeeded
				$this->fillSession($this, $login);

				if (strlen($redirect) <= 0)
					$redirect = $this->default_redirect;
				redirect($redirect);
			}
		}
		else {
			// Validation Failed
			$flashdata->status_type = "error";
			$flashdata->status = $this->form_validation->error_string();
			$this->session->set_flashdata($flashdata);
			redirect($this->loginPage);
		}
		$this->load->view('layout', $data);
	}

	private function register() {
		
		$rules['username'] 	= 'trim|required|callback_check_username';
		$rules['email'] 	= 'trim|required|callback_check_email';
		$rules['password'] 	= 'trim|required|matches[password2]';
		$rules['password2'] = 'trim|required';
		$rules['question'] 	= 'trim|required';
		$rules['answer'] 	= 'trim|required';
			
		$this->validation->set_rules($rules);
		$this->validation->set_error_delimiters('<p class="error">', '</p>');
			
		if($this->validation->run())
		{
			/* $register = TODO:: 
			(
				$this->input->post('username'),
				$this->input->post('password'),
				$this->input->post('email'),
				$this->input->post('question'),
				$this->input->post('answer')
			);
			*/
			
			switch($register)
			{
				case 'REGISTRATION_SUCCESS':
					redirect('');
				case 'REGISTRATION_SUCCESS_EMAIL':
					redirect('');
				default: // Failed
					redirect('');
			}
		}
		else
		{
			$data['content'] = $this->load->view('register', '', true);
			$this->load->view('layout', $data);
		}
	}



	private function internalLogin($username, $password) {
		$sql = "SELECT id, hash as hashvalue, password FROM ".$this->tblu." WHERE username = ?";
		$query = $this->db->query($sql, array($username));
		$res = $query->result();
		
		// Does username exist?
		if (sizeof($res) === 1) {
			$db_id = $res[0]->id;
			$db_hash = $res[0]->hashvalue;
			$db_password = $res[0]->password;
			$enc_password = sha1($this->salt.$db_hash.$password);

			// Check Password
			if ($db_password === $enc_password)
				return $db_id; 
			else
				return false;
			
		} else {
			return false;
		}
			
	}

	public static function fillSession($controller, $id) {
		// must be synchronized with MY_Controller->getUserdataObjectFromSession() 
		$sql = "SELECT id, username, name, email, settings, groupname FROM ".$controller->tblu." WHERE id = ?";
		$query = $controller->db->query($sql, array($id));
		$res = $query->result();
		$u = json_decode($res[0]->settings);
		
		$u = array();
        $u[USERDATA_SESSIONPREFIX.'id']           = $res[0]->id;
        $u[USERDATA_SESSIONPREFIX.'username']     = $res[0]->username;
        $u[USERDATA_SESSIONPREFIX.'name']         = $res[0]->name;
        $u[USERDATA_SESSIONPREFIX.'email']        = $res[0]->email;
        $u[USERDATA_SESSIONPREFIX.'groupname']    = $res[0]->groupname;
		
		$controller->session->set_userdata($u);

		// Set fromUser to user_id
		$controller->session->set_userdata("fromUser", $u[USERDATA_SESSIONPREFIX.'id']);
	}



	function changeview($name) {
		$key = USERDATA_SESSIONPREFIX.'viewname';
		$value = $name;
		$this->session->set_userdata($key, $value);
		redirect($this->loginPage);
	}	


	private function generatePW($length = 6) {
		$dummy = array_merge(range('0', '9'), range('a', 'z'), array('-','+'));
		mt_srand((double)microtime()*1000000);
		for ($i = 1; $i <= (count($dummy)*2); $i++) {
			$swap = mt_rand(0,count($dummy)-1);
			$tmp = $dummy[$swap];
			$dummy[$swap] = $dummy[0];
			$dummy[0] = $tmp;
		}
		return substr(implode('',$dummy),0,$length); 
	}
}



